package org.budo.sms.service.duanyun;

import java.util.Map;

import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.java.net.util.UrlEncodeUtil;
import org.budo.time.Time;
import org.springframework.util.DigestUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public class BudoDuanyunSmsServiceImpl implements BudoDuanyunSmsService {
    private static final String API_URL = "http://send.186b.com/v2sms.aspx";

    private String userId;

    private String username;

    private String password;

    @Override
    public String sendSms(String to, String template, Map<String, Object> parameters) {
        String now = Time.now().toString("yyyyMMddHHmmss");

        String url = API_URL //
                + "?timestamp=" + now //
                + "&Userid=" + this.getUserId()//
                + "&Mobile=" + to //
                + "&content=" + UrlEncodeUtil.encode(template) //
                + "&Sign=" + this.sign(now) //
                + "&Action=send";

        Request request = new Request();
        request.setMethod(Request.POST);
        request.setUrl(url);

        Response response = request.execute();

        String responseBody = response.getBody();

        log.info("#27 response=" + response + ", request=" + request);
        return responseBody;
    }

    @Override
    public String queryStatus() {
        String now = Time.now().toString("yyyyMMddHHmmss");

        String url = "http://send.186b.com/v2statusApi.aspx" //
                + "?timestamp=" + now //
                + "&Userid=" + this.getUserId()//
                + "&Sign=" + this.sign(now) //
                + "&Action=query";

        Request request = new Request();
        request.setMethod(Request.POST);
        request.setUrl(url);

        Response response = request.execute();

        String responseBody = response.getBody();

        log.info("#27 response=" + response + ", request=" + request);
        return responseBody;
    }

    private String sign(String now) {
        String input = this.getUsername() + this.getPassword() + now;
        return DigestUtils.md5DigestAsHex(input.getBytes());
    }
}